/*
对话聊天的路由组件
 */

import React, { Component } from "react";
import { NavBar, List, Grid, Icon } from "antd-mobile";
import { Input, Popover, Avatar, Button } from "antd";
import { connect } from "react-redux";
import QueueAnim from "rc-queue-anim";

import { sendMsg, readMsg } from "../../redux/actions";

const Item = List.Item;
const { TextArea } = Input;

class Chat extends Component {
  state = {
    content: "",
    isShow: false,
  };

  componentWillMount() {
    const { chatMsgs } = this.props.chat;
    const { type, username, _id ,company} = this.props.user;
    const targetId = Number(this.props.match.params.userid);
    const chatId = [_id, targetId].sort().join("_");
    const msgs = chatMsgs.filter((msg) => msg.chat_id === chatId);
    const emojis = [
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
      "😀",
      "😁",
      "🤣",
    ];
    this.emojis = emojis.map((emoji) => ({ text: emoji }));
    if (msgs.length === 0) {
      if (type === "laoban")
        this.setState({ content: `你好我是${company}公司的${username}，看到你的求职信息，可否深入聊聊` });
      if (type === "dashen")
        this.setState({ content: `您好，看到您的招聘信息，希望可以进一步沟通` });
    }
  }

  msgShow = (msg) => {
    let arr = [];
    let tmp;
    let msgTmp = msg;
    if (msg.length > 20) {
      for (let i = 0; i < msg.length / 20; i++) {
        tmp = msgTmp.substr(0, 20);
        arr.push(tmp);
        msgTmp = msgTmp.slice(20);
      }
    }
    return (
      <span>{msg.length > 20 ? arr.map((item) => <p>{item}</p>) : msg}</span>
    );
  };

  componentDidMount() {
    window.scrollTo(0, document.body.scrollHeight);
  }

  componentDidUpdate() {
    window.scrollTo(0, document.body.scrollHeight);
  }

  componentWillUnmount() {
    const from = this.props.match.params.userid;
    const to = this.props.user._id;
    this.props.readMsg(from, to);
  }

  toggleShow = () => {
    const isShow = !this.state.isShow;
    this.setState({ isShow });
    if (isShow) {
      setTimeout(() => {
        window.dispatchEvent(new Event("resize"));
      }, 0);
    }
  };

  handleSend = () => {
    const from = this.props.user._id;
    const to = Number(this.props.match.params.userid);
    const content = this.state.content.trim();
    this.props.sendMsg({ from, to, content });
    this.setState({
      content: "",
      isShow: false,
    });
  };
  render() {
    const { user } = this.props;
    const { users, chatMsgs } = this.props.chat;
    const { content } = this.state;

    const meId = user._id;
    if (!users[meId]) {
      return null;
    }
    const targetId = Number(this.props.match.params.userid);
    const chatId = [meId, targetId].sort().join("_");

    const msgs = chatMsgs.filter((msg) => msg.chat_id === chatId);

    const targetHeader = users[targetId].header;
    const targetIcon = targetHeader
      ? require(`../../assets/images/${targetHeader}.png`)
      : null;
    const meHeader = users[meId].header;
    const meIcon = meHeader
      ? require(`../../assets/images/${meHeader}.png`)
      : null;
    return (
      <div id="chat-page">
        <NavBar
          icon={<Icon type="left" />}
          className="sticky-header"
          onLeftClick={() => this.props.history.goBack()}
        >
          {users[targetId].username}
        </NavBar>
        <List style={{ marginBottom: 50, paddingTop: 50 }}>
          <QueueAnim type="left" delay={100}>
            {msgs.map((msg) => {
              if (targetId === msg.from) {
                return (
                  <Item
                    key={msg._id}
                    style={{
                      height: `${50 + (msg.content.length / 20) * 22}px`,
                    }}
                  >
                    <Popover
                      placement="left"
                      content={this.msgShow(msg.content)}
                      visible={true}
                    >
                      <Avatar src={targetIcon} />
                    </Popover>
                  </Item>
                );
              } else {
                return (
                  <Item
                    key={msg._id}
                    style={{
                      height: `${50 + (msg.content.length / 20) * 22}px`,
                    }}
                  >
                    <Popover
                      placement="right"
                      content={this.msgShow(msg.content)}
                      visible={true}
                    >
                      <Avatar src={meIcon} className="chat-header" />
                    </Popover>
                  </Item>
                );
              }
            })}
          </QueueAnim>
        </List>

        <div className="am-tab-bar">
          <TextArea
            size="large"
            placeholder="请输入"
            value={content}
            style={{ borderRadius: 10, width: "75%" }}
            onChange={(e) => {
              this.setState({ content: e.target.value });
            }}
            onFocus={() => this.setState({ isShow: false })}
            autoSize={{ minRows: 1, maxRows: 3 }}
          />
          <span>
            <Button shape="circle" icon={"😊"} onClick={this.toggleShow} />
            <Button
              disabled={content === ""}
              type="primary"
              shape="round"
              onClick={this.handleSend}
              size={"small"}
            >
              发送
            </Button>
          </span>

          {this.state.isShow && (
            <Grid
              data={this.emojis}
              columnNum={8}
              carouselMaxRow={4}
              isCarousel={true}
              onClick={(item) => {
                this.setState({
                  content: this.state.content + " " + item.text,
                });
              }}
            />
          )}
        </div>
      </div>
    );
  }
}

export default connect((state) => ({ user: state.user, chat: state.chat }), {
  sendMsg,
  readMsg,
})(Chat);
